package com.example.shuiyin.service.impl;

import com.example.shuiyin.dto.MediaMetadata;
import com.example.shuiyin.enums.MediaType;
import com.example.shuiyin.exception.AppException;
import com.example.shuiyin.exception.ErrorCode;
import com.example.shuiyin.parsers.MediaParser;
import com.example.shuiyin.parsers.ParserFactory;
import com.example.shuiyin.service.MediaParserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
@RequiredArgsConstructor
@Slf4j
public class MediaParserServiceImpl implements MediaParserService {

    private final ParserFactory parserFactory;
    
    @Value("${storage.local.path}")
    private String storageBasePath;

    @Override
    public String parseUrl(String url) {
        MediaParser parser = parserFactory.getParser(url);
        if (parser == null) {
            throw new AppException("无效的文件路径", ErrorCode.INVALID_PARAMETER);
        }
        
        MediaParser.MediaInfo mediaInfo = parser.parse(url);
        return mediaInfo.getDownloadUrl();
    }

    @Override
    public MediaType detectMediaType(String url) {
        MediaParser parser = parserFactory.getParser(url);
        if (parser == null) {
            throw new AppException("不支持的媒体类型", ErrorCode.INVALID_PARAMETER);
        }
        
        MediaParser.MediaInfo mediaInfo = parser.parse(url);
        return mediaInfo.getMediaType();
    }

    @Override
    public String downloadMedia(String url) {
        try {
            Path tempDir = Paths.get(storageBasePath, "temp");
            Files.createDirectories(tempDir);
            
            String filename = UUID.randomUUID().toString();
            
            // 从URL判断文件类型
            if (url.contains(".mp4") || url.contains("video")) {
                filename += ".mp4";
            } else if (url.contains(".jpg") || url.contains("image")) {
                filename += ".jpg";
            } else if (url.contains(".png")) {
                filename += ".png";
            } else {
                filename += ".dat";
            }
            
            Path targetPath = tempDir.resolve(filename);
            
            // 下载文件
            try (InputStream in = new URL(url).openStream()) {
                Files.copy(in, targetPath, StandardCopyOption.REPLACE_EXISTING);
            }
            
            return targetPath.toString();
        } catch (Exception e) {
            log.error("下载媒体文件失败: {}", e.getMessage(), e);
            throw new AppException("无效的文件路径", ErrorCode.INVALID_PARAMETER);
        }
    }

    @Override
    public MediaMetadata parseMetadata(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            throw new AppException("无效的文件路径", ErrorCode.INVALID_PARAMETER);
        }
        
        // 根据文件扩展名判断媒体类型
        MediaType mediaType = getMediaTypeFromExtension(filePath);
        if (mediaType == null) {
            throw new AppException("不支持的媒体类型", ErrorCode.INVALID_PARAMETER);
        }
        
        // 其余代码...
        return new MediaMetadata(); // 临时返回空对象，实际实现应该解析并返回文件元数据
    }

    /**
     * 根据文件扩展名获取媒体类型
     * @param filePath 文件路径
     * @return 媒体类型
     */
    private MediaType getMediaTypeFromExtension(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            return null;
        }
        
        String lowerCase = filePath.toLowerCase();
        
        if (lowerCase.endsWith(".mp4") || lowerCase.endsWith(".avi") || 
            lowerCase.endsWith(".mov") || lowerCase.endsWith(".wmv") || 
            lowerCase.endsWith(".flv") || lowerCase.endsWith(".mkv")) {
            return MediaType.VIDEO;
        } else if (lowerCase.endsWith(".jpg") || lowerCase.endsWith(".jpeg") || 
                   lowerCase.endsWith(".png") || lowerCase.endsWith(".gif") || 
                   lowerCase.endsWith(".bmp") || lowerCase.endsWith(".webp")) {
            return MediaType.IMAGE;
        } else if (lowerCase.endsWith(".mp3") || lowerCase.endsWith(".wav") || 
                   lowerCase.endsWith(".ogg") || lowerCase.endsWith(".aac") || 
                   lowerCase.endsWith(".flac")) {
            return MediaType.AUDIO;
        } else if (lowerCase.endsWith(".pdf")) {
            return MediaType.PDF;
        } else {
            return null;
        }
    }

    @Override
    public String extractKeyframe(String videoPath, String outputPath) {
        if (videoPath == null || videoPath.isEmpty()) {
            throw new AppException("无效的文件路径", ErrorCode.INVALID_PARAMETER);
        }
        
        // 临时实现，实际应该使用FFmpeg等工具提取视频关键帧
        return outputPath + "/keyframe.jpg";
    }
} 